﻿using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.Linq;

namespace Flare.DB
{
    class equipment_marks
    {
        public IEnumerable<CeEntity.equipment_mark> Index(int? id_type = null)
        {
            var result = from m in Source.equipment_mark()
                         where m.id_type == id_type
                         select m;
            return result;
        }

        public List<Entity.EquipmentMark> Index2(int? id_type = null)
        {
            using (SqlCeConnection connection = new SqlCeConnection(glob.DBConnection))
            {
                using (SqlCeCommand command = new SqlCeCommand(@"SELECT [id_mark],[id_type],[mark] FROM [equipment_mark] WHERE id_type = @id_type OR @id_type IS NULL", connection))
                {
                    command.Parameters.Add("@id_type", System.Data.SqlDbType.Int).Value = (id_type == null) ? DBNull.Value : (object)id_type;
                    try
                    {
                        connection.Open();
                    }
                    catch (Exception ex)
                    {
                        glob.kernel.Panic(glob.PanicType.db_connect, ex);
                    }
                    var equipmentmarks = new List<Entity.EquipmentMark>();
                    try
                    {
                        using (SqlCeDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                var current_mark = new Entity.EquipmentMark();
                                current_mark.id_mark = Convert.ToInt32(reader["id_mark"]);
                                current_mark.id_type = Convert.ToInt32(reader["id_type"]);
                                current_mark.mark = reader["mark"].ToString();
                                equipmentmarks.Add(current_mark);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(command.CommandText);
                        glob.kernel.Panic(glob.PanicType.sql, ex);
                    }
                    return equipmentmarks;
                }
            }
        }

        public void Create(Entity.EquipmentMark data)
        {
            data.id_mark = 0;
            var validate = data.Validate();
            if (validate.Count() != 0)
            {
                throw new Exception(string.Join<string>("\n", validate));
            }
            using (SqlCeConnection connection = new SqlCeConnection(glob.DBConnection))
            {
                using (SqlCeCommand command = new SqlCeCommand(string.Format("INSERT INTO [equipment_mark] ([mark], [id_type]) VALUES ('{0}',{1})", data.mark, data.id_type), connection))
                {
                  	try
                    {
                        connection.Open();
                    }
                    catch (Exception ex)
                    {
                        glob.kernel.Panic(glob.PanicType.db_connect, ex);
                    }

                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(command.CommandText + "\n" +ex.Message);
                        throw new Exception("Во время добавления данных произошла ошибка. Данные не сохранены");
                    }
                }
            }
        }

        public void Edit(Entity.EquipmentMark data)
        {
            var validate = data.Validate();
            if (validate.Count() != 0)
            {
                throw new Exception(string.Join<string>("\n", validate));
            }

            using (SqlCeConnection connection = new SqlCeConnection(glob.DBConnection))
            {
                using (SqlCeCommand command = new SqlCeCommand(
                        string.Format("UPDATE [equipment_mark] SET [mark] = '{1}', [id_type] = {2} WHERE [id_mark]= {0}", data.id_mark, data.mark, data.id_type), connection))
                {
                    try
                    {
                        connection.Open();
                    }
                    catch (Exception ex)
                    {
                        glob.kernel.Panic(glob.PanicType.db_connect, ex);
                    }

                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(command.CommandText + "\n" +ex.Message);
                        throw new Exception("Во время обновления данных произошла ошибка. Данные не сохранены");
                    }
                }
            }
        }

        public void Delete(int id_mark)
        {
            using (SqlCeConnection connection = new SqlCeConnection(glob.DBConnection))
            {
                using (SqlCeCommand command = new SqlCeCommand(
                    string.Format("DELETE FROM [equipment_mark] WHERE [id_mark] = {0}", id_mark), connection))
                {
                  	try
                    {
                        connection.Open();
                    }
                    catch (Exception ex)
                    {
                        glob.kernel.Panic(glob.PanicType.db_connect, ex);
                    }

                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(command.CommandText + "\n" +ex.Message);
                        throw new Exception("Во время удаления данных произошла ошибка. Данные не сохранены");
                    }
                }
            }
        }

    }
}
